<template>
  <div class="file-replace">
    <div class="file-section">
      <div class="form-group">
        <label for="original-file">
          <i class="icon">📄</i>
          选择原始文件 (strings.xml)：
        </label>
        <input 
          type="file" 
          id="original-file" 
          ref="originalFileInput" 
          @change="handleOriginalFileUpload" 
          accept=".xml" 
        />
        <div v-if="originalFile" class="file-info">
          <span class="file-name">{{ originalFile.name }}</span>
          <span class="file-size">({{ formatFileSize(originalFile.size) }})</span>
        </div>
      </div>

      <div class="form-group">
        <label for="replace-file">
          <i class="icon">🔄</i>
          选择替换文件 (strings.xml)：
        </label>
        <input 
          type="file" 
          id="replace-file" 
          ref="replaceFileInput" 
          @change="handleReplaceFileUpload" 
          accept=".xml" 
        />
        <div v-if="replaceFile" class="file-info">
          <span class="file-name">{{ replaceFile.name }}</span>
          <span class="file-size">({{ formatFileSize(replaceFile.size) }})</span>
        </div>
      </div>
    </div>

    <button 
      @click="processFiles" 
      :disabled="!originalFile || !replaceFile || processing"
      class="process-button"
    >
      <span v-if="processing">处理中...</span>
      <span v-else>
        <i class="icon">⚡</i>
        开始替换字符串
      </span>
    </button>

    <div v-if="processing" class="progress">
      <div class="progress-bar" :style="{ width: progress + '%' }"></div>
      <div class="progress-text">{{ progress }}%</div>
    </div>

    <div v-if="message" class="message" :class="messageType">
      {{ message }}
    </div>

    <div class="help-section">
      <h3>使用说明：</h3>
      <ul>
        <li>📁 选择需要被替换的原始 strings.xml 文件</li>
        <li>🔄 选择包含新字符串内容的替换文件</li>
        <li>⚡ 点击"开始替换字符串"按钮进行处理</li>
        <li>💾 处理完成后会自动下载替换后的文件</li>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  name: 'FileReplace',
  data() {
    return {
      originalFile: null,
      replaceFile: null,
      processing: false,
      progress: 0,
      message: '',
      messageType: 'success'
    };
  },
  methods: {
    handleOriginalFileUpload(event) {
      this.originalFile = event.target.files[0];
      this.clearMessage();
    },
    
    handleReplaceFileUpload(event) {
      this.replaceFile = event.target.files[0];
      this.clearMessage();
    },
    
    formatFileSize(bytes) {
      if (bytes === 0) return '0 Bytes';
      const k = 1024;
      const sizes = ['Bytes', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },
    
    processFiles() {
      if (!this.originalFile || !this.replaceFile) {
        this.showMessage('请选择原始文件和替换文件', 'error');
        return;
      }

      this.processing = true;
      this.progress = 0;
      this.clearMessage();

      const formData = new FormData();
      formData.append('original_file', this.originalFile);
      formData.append('replace_file', this.replaceFile);

      const xhr = new XMLHttpRequest();
      xhr.open('POST', `${window.VUE_APP_API_BASE_URL}/replace`, true);
      xhr.responseType = 'blob';

      xhr.upload.onprogress = (event) => {
        if (event.lengthComputable) {
          this.progress = Math.round((event.loaded / event.total) * 50); // 上传占50%
        }
      };

      xhr.onprogress = (event) => {
        if (event.lengthComputable) {
          this.progress = 50 + Math.round((event.loaded / event.total) * 50); // 下载占50%
        }
      };

      xhr.onload = () => {
        this.processing = false;
        this.progress = 100;
        
        if (xhr.status === 200) {
          // 成功处理，下载文件
          const url = window.URL.createObjectURL(new Blob([xhr.response]));
          const a = document.createElement('a');
          a.href = url;
          
          // 生成下载文件名
          const originalName = this.originalFile.name.replace('.xml', '');
          a.download = `${originalName}_replaced.xml`;
          
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
          window.URL.revokeObjectURL(url);
          
          this.showMessage('字符串替换完成，文件已下载！', 'success');
          this.resetForm();
        } else {
          // 处理错误响应
          const reader = new FileReader();
          reader.onload = () => {
            try {
              const errorData = JSON.parse(reader.result);
              this.showMessage(errorData.error || '处理失败', 'error');
            } catch (e) {
              this.showMessage('处理失败，请检查文件格式', 'error');
            }
          };
          reader.readAsText(xhr.response);
        }
      };

      xhr.onerror = () => {
        this.processing = false;
        this.progress = 0;
        this.showMessage('网络错误，请重试', 'error');
      };

      xhr.send(formData);
    },
    
    resetForm() {
      // 重置文件输入
      if (this.$refs.originalFileInput) {
        this.$refs.originalFileInput.value = '';
      }
      if (this.$refs.replaceFileInput) {
        this.$refs.replaceFileInput.value = '';
      }
      
      this.originalFile = null;
      this.replaceFile = null;
      this.progress = 0;
      
      // 3秒后清除消息
      setTimeout(() => {
        this.clearMessage();
      }, 3000);
    },
    
    showMessage(text, type = 'success') {
      this.message = text;
      this.messageType = type;
    },
    
    clearMessage() {
      this.message = '';
    }
  }
};
</script>

<style scoped>
.file-replace {
  max-width: 600px;
  margin: 0 auto;
}

.file-section {
  margin-bottom: 30px;
}

.form-group {
  margin-bottom: 25px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
  font-size: 16px;
}

.icon {
  margin-right: 8px;
  font-size: 18px;
}

input[type="file"] {
  width: 100%;
  padding: 12px;
  font-size: 14px;
  border: 2px dashed #ccc;
  border-radius: 10px;
  background-color: #fafafa;
  color: #555;
  transition: all 0.3s ease;
  cursor: pointer;
}

input[type="file"]:hover {
  border-color: #4285f4;
  background-color: #f0f8ff;
}

input[type="file"]:focus {
  outline: none;
  border-color: #4285f4;
  box-shadow: 0 0 0 3px rgba(66, 133, 244, 0.1);
}

.file-info {
  margin-top: 8px;
  padding: 8px 12px;
  background-color: #e8f5e8;
  border-radius: 6px;
  border-left: 4px solid #4caf50;
}

.file-name {
  font-weight: 500;
  color: #2e7d32;
}

.file-size {
  color: #666;
  margin-left: 8px;
  font-size: 13px;
}

.process-button {
  width: 100%;
  padding: 15px;
  font-size: 16px;
  font-weight: 500;
  border: none;
  border-radius: 10px;
  background: linear-gradient(135deg, #4285f4, #34a853);
  color: white;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 20px;
  box-shadow: 0 4px 15px rgba(66, 133, 244, 0.3);
}

.process-button:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(66, 133, 244, 0.4);
}

.process-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.progress {
  position: relative;
  height: 8px;
  background-color: #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 20px;
}

.progress-bar {
  height: 100%;
  background: linear-gradient(90deg, #4285f4, #34a853);
  border-radius: 4px;
  transition: width 0.3s ease;
}

.progress-text {
  position: absolute;
  top: -25px;
  right: 0;
  font-size: 12px;
  color: #666;
  font-weight: 500;
}

.message {
  padding: 12px 16px;
  border-radius: 8px;
  margin-bottom: 20px;
  font-weight: 500;
}

.message.success {
  background-color: #e8f5e8;
  color: #2e7d32;
  border-left: 4px solid #4caf50;
}

.message.error {
  background-color: #ffebee;
  color: #c62828;
  border-left: 4px solid #f44336;
}

.help-section {
  margin-top: 40px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 10px;
  border-left: 4px solid #4285f4;
}

.help-section h3 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 18px;
}

.help-section ul {
  margin: 0;
  padding-left: 20px;
}

.help-section li {
  margin-bottom: 8px;
  color: #555;
  line-height: 1.5;
}
</style>
